import Tips from './Tips';
import auth from '../api/auth'
const app = getApp();
const TOKEN = uni.getStorageSync('AUTH_TOKEN')
// HTTP工具类
export default class http {
  static async request (method, url, data = {}) {
    const param = {
      url: url,
      method: method,
      header: {
        // 'Content-Type': 'application/json',
        // 'Authorization': uni.getStorageSync('AUTH_TOKEN'),
        'token': uni.getStorageSync('AUTH_TOKEN'),
        'platform': 'toker',
        // 'authorization': TOKEN || '22222'
      },
      data: data
    };
    const muted = data.muted;
    delete param.data.muted;

    Tips.loading();
    const res = await uni.request(param);
    Tips.loaded();
    if (this.isSuccess(res)) {
      if(res[1].data.codeId === 200) {
        return res[1].data.resData;
      }
    } else {
      if(res[1].data.codeId === -99) {
        uni.clearStorageSync()
        uni.reLaunch({url: '/subPackages/Login/index'})
      } 
      uni.showToast({title: res[1].data.codeDes, icon:"none"})
      // return res[1].data;
      throw this.requestException(res);
    }
  }

  /**
   * 判断请求是否成功
   */
  static isSuccess(res) {
    const wxCode = res[1].statusCode
        // 微信请求错误
    if (wxCode !== 200) {
        return false;
    }
    const wxData = res[1].data;
    return wxData && (wxData.code === 200 || wxData.codeId === 200);
  }

  /**
   * 异常
   */
  static requestException(res) {
    const error = {};
    error.statusCode = res.statusCode;
    const wxData = res[1].data;
    if (wxData) {
      error.serverCode = wxData.codeId;
      error.message = wxData.codeDes;
      error.serverData = wxData;
    }
    return error;
  }

  static get (url, data) {
    return this.request('GET', url, data)
  }

  static put (url, data) {
    return this.request('PUT', url, data)
  }

  static post (url, data) {
    return this.request('POST', url, data)
  }

  static patch (url, data) {
    return this.request('PATCH', url, data)
  }

  static delete (url, data) {
    return this.request('DELETE', url, data)
  }
}
